<template>
  <div class="singer-container">
    <!-- 顶部筛选区域 -->
    <div class="filter-section">
      <!-- 分类标签（音乐风格） -->
      <div class="category-filter">
        <div class="custom-category-tabs">
          <span
            v-for="category in categories"
            :key="category.id"
            :class="[
              'custom-category-tab',
              { active: activeCategory === category.id },
            ]"
            @click="selectCategory(category.id)"
          >
            {{ category.name }}
          </span>
        </div>
      </div>
    </div>

    <!-- 歌手列表 -->
    <div class="singer-list">
      <el-row :gutter="24">
        <el-col
          v-for="singer in filteredSingers"
          :key="singer.id"
          :xs="24"
          :sm="12"
          :md="6"
          :lg="6"
          :xl="6"
        >
          <div
            class="singer-card square-card"
            @click="goToSingerDetail(singer.id)"
          >
            <div class="avatar-container square-avatar">
              <el-image :src="singer.avatar" class="singer-avatar" fit="cover">
                <template #error>
                  <div class="avatar-error">
                    <el-icon><User /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="singer-info">
              <h3 class="singer-name">{{ singer.name }}</h3>
              <div class="singer-meta">
                <span class="fans-count">
                  <el-icon><User /></el-icon>
                  {{ formatNumber(singer.fansCount) }} 粉丝
                </span>
              </div>
              <div class="singer-genres">
                <el-tag
                  v-for="(genre, index) in singer.genres"
                  :key="index"
                  type="info"
                  size="small"
                >
                  {{ genre }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="totalSingers"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import {
  getArtistGenres,
  getArtistList,
  getArtistsByGenreMatch,
} from "@/services/api";
import { User } from "@element-plus/icons-vue";
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();

// 筛选状态
const activeCategory = ref("all");
const currentPage = ref(1);
const pageSize = ref(12);
const totalSingers = ref(0);
// 标签点击切换
const selectCategory = (id) => {
  if (activeCategory.value !== id) {
    activeCategory.value = id;
    currentPage.value = 1;
    fetchSingers();
  }
};

// 歌手分类（音乐风格）
const categories = ref([]);
// 歌手数据
const singers = ref([]);
const filteredSingers = computed(() => singers.value);

// loading & error 状态
const loading = ref(false);
const error = ref(null);

// 获取歌手分类标签（音乐风格）
const fetchCategories = async () => {
  try {
    loading.value = true;
    const res = await getArtistGenres();
    console.log("歌手分类标签加载成功:", res);
    // 适配后端返回格式：['全部','Pop',...]，转为{id, name}
    if (Array.isArray(res.data)) {
      categories.value = res.data
        .filter((item) => item !== "全部")
        .map((item) => ({ id: item, name: item }));
      // 保证有全部选项
      categories.value.unshift({ id: "", name: "全部" });
    } else {
      categories.value = [];
    }
    error.value = null;
  } catch (e) {
    error.value = "获取歌手分类失败";
  } finally {
    loading.value = false;
  }
};

// 获取歌手列表
const fetchSingers = async () => {
  try {
    loading.value = true;
    let res;
    if (activeCategory.value !== "all") {
      // 按风格标签精准获取歌手
      res = await getArtistsByGenreMatch({
        genre: activeCategory.value,
        limit: pageSize.value,
      });
      console.log("按风格标签获取歌手:", res);
      singers.value = Array.isArray(res.data)
        ? res.data.map((item) => ({
            id: item.artistId,
            name: item.artistName,
            avatar: item.avatarUrl,
            genres: item.genre ? item.genre.split(",") : [],
            fansCount: item.followerCount || 0,
          }))
        : [];
      totalSingers.value = singers.value.length;
    } else {
      // 全部歌手
      const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
      };
      res = await getArtistList(params);
      console.log("全部歌手列表加载成功:", res);
      singers.value = Array.isArray(res.data?.list)
        ? res.data.list.map((item) => ({
            id: item.artistId,
            name: item.artistName,
            avatar: item.avatarUrl,
            genres: item.genre ? item.genre.split(",") : [],
            fansCount: item.fans_count || 0,
          }))
        : [];
      totalSingers.value = res.data?.total || 0;
    }
    error.value = null;
  } catch (e) {
    error.value = "获取歌手列表失败";
  } finally {
    loading.value = false;
  }
};

// 格式化数字
const formatNumber = (num) => {
  if (num >= 10000000) return `${(num / 10000000).toFixed(1)}千万`;
  if (num >= 10000) return `${(num / 10000).toFixed(1)}万`;
  return num;
};

// 跳转到歌手详情页
const goToSingerDetail = (artistId) => {
  if (!artistId) {
    ElMessage.error("歌手信息异常");
    return;
  }
  router.push({
    name: "SingerDetail",
    params: { id: artistId },
    query: { from: router.currentRoute.value.fullPath },
  });
};

// 筛选歌手
const filterSingers = () => {
  currentPage.value = 1;
  fetchSingers();
};

// 处理分页变化
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  fetchSingers();
  window.scrollTo({ top: 0, behavior: "smooth" });
};

onMounted(async () => {
  await fetchCategories();
  // 自动选中第一个分类（全部标签）并加载歌手
  if (categories.value.length > 0) {
    activeCategory.value = categories.value[0].id;
    currentPage.value = 1;
    await fetchSingers();
  }
});
</script>

<style scoped>
.singer-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.filter-section {
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.03);
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-header h1 {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin: 0;
}

.alphabet-filter,
.category-filter,
.region-filter {
  margin-bottom: 15px;
}

.alphabet-filter .el-radio-group,
.category-filter .el-radio-group,
.region-filter .el-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.alphabet-filter .el-radio-button,
.category-filter .el-radio-button,
.region-filter .el-radio-button {
  margin-bottom: 8px;
}

.singer-list {
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.03);
}

/* 自定义风格标签样式 */
.custom-category-tabs {
  display: flex;
  justify-content: center;
  color: #b8aeec;
  background: #ffffff;
  align-items: center;
  gap: 32px;
  padding: 10px 0 0 0;
}
.custom-category-tab {
  font-size: 22px;
  color: #333;
  font-weight: 400;
  cursor: pointer;
  padding: 0 4px 6px 4px;
  transition: color 0.2s, font-weight 0.2s;
  border: none;
  background: none;
  outline: none;
  position: relative;
}
.custom-category-tab.active {
  font-weight: 700;
  color: #111;
}
.custom-category-tab.active::after {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 3px;
  background: #111;
  border-radius: 2px;
}
.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.list-header h2 {
  font-size: 20px;
  font-weight: 700;
  color: #333;
  margin: 0;
}

/* 歌手卡片正方形布局 */
.singer-card.square-card {
  background: #fff;
  border-radius: 12px;
  padding: 0;
  margin-bottom: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 0;
  padding-bottom: 100%; /* 正方形 */
  position: relative;
  border: 1px solid #f0f2f5;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.03);
  overflow: hidden;
  display: block;
}

.singer-card.square-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  border-color: #ebeef5;
}

.avatar-container.square-avatar {
  width: 100%;
  height: 60%;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  border-radius: 0;
  overflow: hidden;
}

.singer-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 0;
  background: #f0f2f5;
  transition: transform 0.5s ease;
}

.singer-card.square-card:hover .singer-avatar {
  transform: scale(1.05);
}

.singer-info {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 40%;
  background: rgba(255, 255, 255, 0.96);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8px 4px 4px 4px;
  box-sizing: border-box;
}

.singer-name {
  font-size: 16px;
  font-weight: 700;
  margin: 0 0 6px 0;
  color: #333;
  text-align: center;
  flex-grow: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.singer-meta {
  display: flex;
  justify-content: center;
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.singer-meta span {
  display: flex;
  align-items: center;
}

.singer-meta .el-icon {
  margin-right: 4px;
  font-size: 12px;
}

.singer-genres {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
}

.singer-genres .el-tag {
  margin: 0;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
  font-size: 11px;
}

@media (max-width: 1200px) {
  .el-col[xl="6"] {
    max-width: 25%;
    flex: 0 0 25%;
  }
}

@media (max-width: 992px) {
  .el-col[lg="6"] {
    max-width: 33.3333%;
    flex: 0 0 33.3333%;
  }
}

@media (max-width: 768px) {
  .el-col[md="6"] {
    max-width: 50%;
    flex: 0 0 50%;
  }
  .singer-avatar {
    height: 100%;
  }
}

@media (max-width: 576px) {
  .el-col[sm="12"] {
    max-width: 100%;
    flex: 0 0 100%;
  }
  .singer-avatar {
    height: 100%;
  }
}

.avatar-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f2f5;
  color: #c0c4cc;
  font-size: 40px;
}

.singer-name {
  font-size: 16px;
  font-weight: 700;
  margin: 0 0 10px;
  color: #333;
  text-align: center;
  flex-grow: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.singer-meta {
  display: flex;
  justify-content: center;
  font-size: 12px;
  color: #666;
  margin-bottom: 10px;
}

.singer-meta span {
  display: flex;
  align-items: center;
}

.singer-meta .el-icon {
  margin-right: 4px;
  font-size: 12px;
}

.singer-genres {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  justify-content: center;
}

.singer-genres .el-tag {
  margin: 2px;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

@media (max-width: 768px) {
  .filter-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-header h1 {
    margin-bottom: 15px;
  }

  .list-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .singer-avatar {
    height: 160px;
  }
}

@media (max-width: 576px) {
  .singer-container {
    padding: 10px;
  }

  .filter-section,
  .singer-list {
    padding: 15px;
  }

  .singer-avatar {
    height: 140px;
  }

  .singer-name {
    font-size: 14px;
  }
}
</style>
